package com.imooc.user.controller.center;

import com.imooc.controller.BaseController;
import com.imooc.user.pojo.Users;
import com.imooc.user.pojo.bo.center.CenterUserBO;
import com.imooc.user.resource.FileUpload;
import com.imooc.user.service.center.CenterUserService;
import com.imooc.utils.CookieUtils;
import com.imooc.utils.DateUtil;
import com.imooc.pojo.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.imooc.utils.DateUtil.DATE_PATTERN;

@Api(value = "用户信息接口", tags = {"用户信息相关接口"})
@RestController
@RequestMapping("/userInfo")
public class CenterUserController extends BaseController {

    @Autowired
    private CenterUserService centerUserService;

    //映射类
    @Autowired
    private FileUpload fileUpload;

    @ApiOperation(value = "用户头像修改", notes = "用户头像修改", httpMethod = "POST")
    @PostMapping("/uploadFace")
    public IMOOCJSONResult update(
            @ApiParam(name = "userId", value = "用户id", required = true)
            @RequestParam String userId,
            @ApiParam(name = "file", value = "用户头像", required = true)
                    MultipartFile file,
            HttpServletRequest request, HttpServletResponse response) {

        // 头像报错的地址
//        String fileSpace = IMAGE_USER_FACE_LOCATION;
        String fileSpace = fileUpload.getImageUserFaceLocation();//获取配置文件中的目录

        // 在路径下为每一个用户增加一个userId，用于区分不同用户上传
        String uploadPathPrefix = File.separator + userId;

        // 开始文件上传
        if (file != null) {
            FileOutputStream fileOutputStream = null;
            try {
                // 获得文件上传的文件名称
                String fileName = file.getOriginalFilename();

                if (StringUtils.isNotBlank(fileName)) {

                    // 文件重命名 imooc-face.png -> ["imooc-face","png"]
                    String fileNameArr[] = fileName.split("\\.");

                    // 获取文件的后缀名
                    String suffix = fileNameArr[fileNameArr.length - 1];
                    // 判斷後綴名，以防黑客攻擊
                    if (!suffix.equalsIgnoreCase("png") &&
                            suffix.equalsIgnoreCase("jpg") &&
                            suffix.equalsIgnoreCase("jpeg")) {
                        return IMOOCJSONResult.errorMsg("圖片格式不正確");
                    }

                    // imooc-face.png
                    // 文件名称重组 覆盖式上传，增量式上传：额外拼接当前时间
                    String newFileName = "face-" + userId + "." + suffix;

                    // 上传的头像最终保存的位置，File.separator为斜杠的代码写法
                    String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;

                    // 用于提供给web服務訪問的地址
                    uploadPathPrefix += ("/" + newFileName);

                    File outFile = new File(finalFacePath);
                    if (outFile.getParentFile() != null) {
                        // 创建文件夹
                        outFile.getParentFile().mkdirs();
                    }

                    // 文件输出保存到目录
                    fileOutputStream = new FileOutputStream(outFile);
                    InputStream inputStream = file.getInputStream();

                    // 文件保存
                    IOUtils.copy(inputStream, fileOutputStream);

                    // face-{userId}.png

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } else {
            return IMOOCJSONResult.errorMsg("文件不能为空！");
        }

        // 更新用户头像到数据库，要把web服务的地址更新到数据库，否则没法查看图片

        // 获得图片服务地址：http://localhost:8088/foodie/faces
        String imageServerUrl = fileUpload.getImageServerUrl();

        // 由於瀏覽器可能存在緩存的情況，所以在這裡我們需要加上時間戳來保證更新後的圖片及時刷新："?t=" + DateUtil.getCurrentDateString(DATE_PATTERN)
        String finalUserFaceUrl = imageServerUrl + uploadPathPrefix + "?t=" + DateUtil.getCurrentDateString(DATE_PATTERN);

        Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);
        userResult = setNullProperty(userResult);
        // 使用cookie工具类更新前端Cookie中的信息，让他显示更新后的用户信息。isEncode：是否加密
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userResult), true);

        // TODO 后续要改，增加令牌token，会整合进redis，分布式会话

        return IMOOCJSONResult.ok(userResult);
    }


    @ApiOperation(value = "修改用户信息", notes = "修改用户信息", httpMethod = "POST")
    @PostMapping("/update")
    public IMOOCJSONResult update(
            @ApiParam(name = "userId", value = "用户id", required = true)
            @RequestParam String userId,
            @RequestBody @Valid CenterUserBO centerUserBO,
            BindingResult result,//通过@Valid的验证，result包含了前端的验证的错误信息
            HttpServletRequest request, HttpServletResponse response) {

        //判断BindingResult是否包含错误的验证信息，如果有则直接return
        if (result.hasErrors()) {
            Map<String, String> errorMap = getErrors(result);
            return IMOOCJSONResult.errorMap(errorMap);
        }

        Users userResult = centerUserService.updateUserInfo(userId, centerUserBO);
        userResult = setNullProperty(userResult);
        // 使用cookie工具类更新前端Cookie中的信息，让他显示更新后的用户信息。isEncode：是否加密
        CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(userResult), true);

        // TODO 后续要改，增加令牌token，会整合进redis，分布式会话

        return IMOOCJSONResult.ok(userResult);
    }

//    @ApiOperation(value = "修改用户信息", notes = "修改用户信息", httpMethod = "POST")
//    @PostMapping("update")
//    public IMOOCJSONResult update(
//            @ApiParam(name = "userId", value = "用户id", required = true)
//            @RequestParam String userId,
//            @RequestBody @Valid CenterUserBO centerUserBO,
//            BindingResult result,
//            HttpServletRequest request, HttpServletResponse response) {
//
//        System.out.println(centerUserBO);
//
//        // 判断BindingResult是否保存错误的验证信息，如果有，则直接return
//        if (result.hasErrors()) {
//            Map<String, String> errorMap = getErrors(result);
//            return IMOOCJSONResult.errorMap(errorMap);
//        }
//
//        Users userResult = centerUserService.updateUserInfo(userId, centerUserBO);
//
//        userResult = setNullProperty(userResult);
//        CookieUtils.setCookie(request, response, "user",
//                JsonUtils.objectToJson(userResult), true);
//
//        // TODO 后续要改，增加令牌token，会整合进redis，分布式会话
//
//        return IMOOCJSONResult.ok();
//    }


    private Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            //发生验证错误所对应的某一个属性
            String errorField = error.getField();
            // 验证错误的信息
            String errorMsg = error.getDefaultMessage();
            map.put(errorField, errorMsg);
        }
        return map;
    }

    private Users setNullProperty(Users userResult) {
        userResult.setPassword(null);
        userResult.setMobile(null);
        userResult.setEmail(null);
        userResult.setCreatedTime(null);
        userResult.setUpdatedTime(null);
        userResult.setBirthday(null);
        return userResult;
    }

}
